package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.rule.template.RuleTemplateDTO;
import io.github.talelin.latticy.model.RuleTemplateDO;
import io.github.talelin.latticy.mapper.RuleTemplateMapper;
import io.github.talelin.latticy.service.RuleTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@wulongbo
 * @since 2022-08-25
 */
@Service
public class RuleTemplateServiceImpl extends ServiceImpl<RuleTemplateMapper, RuleTemplateDO> implements RuleTemplateService {

    @Override
    public boolean addTemplate(RuleTemplateDTO dto) {
        this.checkRuleTemplateExistByFeesBizTypeAndLevel(dto);
        return this.save(new RuleTemplateDO(dto));
    }

    @Override
    public boolean updateTemplateById(RuleTemplateDTO dto, Integer id) {
        this.checkRuleTemplateExistByFeesBizTypeAndLevel(dto, id);
        return this.updateById(new RuleTemplateDO(dto, id));
    }

    @Override
    public boolean deleteTemplateById(Integer id) {
        return this.removeById(id);
    }

    @Override
    public RuleTemplateDO getTemplateById(Integer id) {
        return this.getById(id);
    }

    @Override
    public IPage<RuleTemplateDO> getTemplatePage(Integer page, Integer count) {
        Page<RuleTemplateDO> pager = new Page<>(page, count);
        return this.baseMapper.selectPage(pager, null);
    }

    @Override
    public String getTemplateNameByFeesBizTypeAndLevel(Integer feesBizType, Integer level) {
        return this.baseMapper.getTemplateNameByFeesBizTypeAndLevel(feesBizType,level);
    }

    private void checkRuleTemplateExistByFeesBizTypeAndLevel(RuleTemplateDTO dto) {
        QueryWrapper<RuleTemplateDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RuleTemplateDO::getFeesBizType, dto.getFeesBizType()).eq(RuleTemplateDO::getLevel, dto.getLevel());
        int count = this.count(wrapper);
        if (count > 0) {
            throw new ForbiddenException(18803);
        }
    }

    private void checkRuleTemplateExistByFeesBizTypeAndLevel(RuleTemplateDTO dto, Integer id) {
        QueryWrapper<RuleTemplateDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RuleTemplateDO::getFeesBizType, dto.getFeesBizType()).eq(RuleTemplateDO::getLevel, dto.getLevel())
                .ne(RuleTemplateDO::getId, id);
        int count = this.count(wrapper);
        if (count > 0) {
            throw new ForbiddenException(18803);
        }
    }
}
